/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 晓星航
 * Date: 2023-10-11
 * Time: 8:57
 */
public class MagicSquare2 {
    public static void main(String[] args) {
        int n = 7; // 魔方的阶数
        int[] magicSquare = new int[n * n]; // 创建一个一维数组作为魔方

        int row = 0; // 初始化行坐标
        int col = n / 2; // 初始化列坐标

        for (int i = 1; i <= n * n; i++) {
            magicSquare[row * n + col] = i;

            int tempRow = row; // 记录当前位置
            int tempCol = col;

            // 判断下一个位置是否越界或已经被填充
            row--;
            col++;
            if (row < 0) {
                row = n - 1;
            }
            if (col > n - 1) {
                col = 0;
            }
            if (magicSquare[row * n + col] != 0) {
                row = tempRow + 1;
                col = tempCol;
                if (row > n - 1) {
                    row = 0;
                }
            }
        }

        // 打印魔方
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(magicSquare[i * n + j] + "\t");
            }
            System.out.println();
        }
    }
}
